package com.usb.qa.java.Kirkov.exam1.model;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MyHandler extends DefaultHandler {
    private String thisString;
    private Product prod = new Product();
    private List<Product> prodList = new ArrayList<Product>();


    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

    }


    @Override
    public void characters(char[] ch, int start, int length) {
        thisString = new String(ch, start, length);

    }


    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equals("name")) {
            prod.setName(thisString);
        } else if (qName.equals("productionCountry")) {
            prod.setProductionCountry(thisString);
        } else if (qName.equals("weight")) {
            prod.setWeight(new Integer(thisString));

        } else if (qName.equals("price")) {
            prod.setPrice(new Integer(thisString));
        } else if (qName.equals("Product")) {
            prod = new Product(prod.getName(), prod.getProductionCountry(), prod.getWeight(), prod.getPrice());
            prodList.add(prod);
            prod=new Product();
        }

    }

    private List<Product> getClearList() throws IOException {
        List<Product> clear=new ArrayList<Product>();
        int id;
        for (Product p:prodList){
            if (!clear.contains(p)){
                clear.add(p);
            }
            else {
                id=p.getId();
                FileOutputStream fos=new FileOutputStream(id+".serialized");
                ObjectOutputStream oos=new ObjectOutputStream(fos);
                oos.writeObject(p);
                oos.flush();
                oos.close();
            }
        }
        return clear;
    }

    @Override
    public void endDocument() throws SAXException {
        try {
            prodList=getClearList();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(prodList);

    }

    public List<Product> getList(){
        return prodList;
    }

}
